package at.kokoni.Koko_Ni.util;

import android.os.AsyncTask;
import at.kokoni.Koko_Ni.entities.Post;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class AsyncLayer extends AsyncTask<Object, Void, String> {

	@Override
	protected String doInBackground(Object... objects) {
		if (objects[0] instanceof String) {
			String function = (String) objects[0];
			if (function.equalsIgnoreCase("get")) {
				return get((String) objects[1]);
			} else if (function.equalsIgnoreCase("post")) {
				return post((String) objects[1], objects[2], (String) objects[3], (String) objects[4]);
			}
		}
		return null;
	}

	private String get(String url) {
		UrlBuilder builder = new UrlBuilder(url);
		RestUtil util = new RestUtil(builder.getUrl());
		return util.get();
	}

	private String post(String url, Object entity, String session, String image) {
		UrlBuilder builder = new UrlBuilder(url);
		RestUtil util = new RestUtil(builder.getUrl());
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		if (entity instanceof Post) {
			Post post = (Post) entity;
			nameValuePairs.add(new BasicNameValuePair("latitude", String.format((Locale) null, "%f", post.getLatitude())));
			nameValuePairs.add(new BasicNameValuePair("longitude", String.format((Locale) null, "%f", post.getLongitude())));
			nameValuePairs.add(new BasicNameValuePair("text", post.getText()));
			nameValuePairs.add(new BasicNameValuePair("session", session));
			if (image != null) {
				nameValuePairs.add(new BasicNameValuePair("image", image));
			}
		}
		return util.post(nameValuePairs);
	}
}
